package eaa.tgi.scrum.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import eaa.tgi.scrum.domain.User;
import eaa.tgi.scrum.exceptions.UserNotFoundException;
import eaa.tgi.scrum.repositories.UserRepository;

@Service
@Transactional
public class UserLoginService {

	@Autowired
	private UserRepository userRepository;
	
	
	public void setUserRepository(UserRepository userRepository) {
		this.userRepository = userRepository;
	}
	
	public User authenticate(User user) throws UserNotFoundException {
		
		User authenticatedUser = userRepository.findByUsernameAndPassword(user.getUsername(), 
																		  user.getPassword());
		if(authenticatedUser == null) {
			throw new UserNotFoundException("Invalid username/password");
		} else {
			authenticatedUser.setStatus("ON");
			userRepository.update(authenticatedUser);
		}
		
		return authenticatedUser;
	}
}

